import sys
from service.setting_das_service import DataDictionaryDasService
from views.common.translator import Translator
from views.template_page_view import BasePageTemplateView, FormItemDto
from common.utils.utils_log import AntLogger
from views.template.data_classes import TableDataDto, ComponentConfig


class CommonSettingDasView(BasePageTemplateView):

    def __init__(self, parent=None):
        t = Translator()
        super().__init__("CommonSettingDasView", parent=parent)
        self.dataMapService = DataDictionaryDasService()

    def doInitAndUpdate(self):
        # 添加设置表单
        self._add_setting_form()

        # 添加设置表格
        self._add_setting_table()

    def _add_setting_form(self):
        """添加设置表单"""
        AntLogger.info("加载Setting页面")

        form_items = self.dataMapService.get_all_common_settings()

        # 使用样式文件创建表单
        form_result = self.addFromTemplate(
            form_items=form_items,
            title="基础配置表单",
            callback=self.commonSettingCallback,
        )

        # 使用封装方法应用样式
        self.apply_style_to_widget(form_result, "form_style.qss")

    def _add_setting_table(self):
        """添加设置表格"""
        # 添加表格
        table_result = self.addTableTemplate(
            title="系统设置列表",
            dataFun=self.get_settings_table_data,
            datParamFun=self.getBaseParam,
            stretch=1,
        )

    def commonSettingCallback(self, form_data: list[FormItemDto]):
        """处理表单提交"""
        AntLogger.info(f"Form Data: {form_data}")
        """
        接收 FormItemDto 列表并保存到数据库。
        """

        for item in form_data:
            # 调用 DataDictionaryService 的保存方法
            try:
                self.dataMapService.save_or_update_common_setting(
                    item.form_key, item.form_value, item.form_desc
                )
                AntLogger.info(f"Saved field: {item.form_key} - {item.form_value}")
            except Exception as e:
                AntLogger.info(f"Failed to save field {item.form_key}. Error: {e}")

        # 刷新表格数据
        self.refreshDataForTemplate("系统设置列表")

    def get_settings_table_data(self, param_dict=None) -> TableDataDto:
        """获取设置表格数据"""
        try:
            # 从数据库获取所有设置
            settings = self.dataMapService._setting_das.get_all_settings()

            # 定义表头
            headers = ["键名", "值", "描述", "创建时间", "更新时间", "操作"]

            # 准备表格数据
            data = []
            for setting in settings:
                # 格式化日期时间
                created_at = (
                    setting.created_at.strftime("%Y-%m-%d %H:%M:%S")
                    if setting.created_at
                    else ""
                )
                updated_at = (
                    setting.updated_at.strftime("%Y-%m-%d %H:%M:%S")
                    if setting.updated_at
                    else ""
                )

                # 添加行数据
                data.append(
                    [
                        setting.setting_key,
                        setting.setting_value or "",
                        setting.setting_desc or "",
                        created_at,
                        updated_at,
                        setting.setting_key,  # 用于操作按钮的标识
                    ]
                )

            # 定义操作按钮
            operations = [{"编辑": self.edit_setting}, {"删除": self.delete_setting}]

            return TableDataDto(
                table_header=headers, table_data=data, table_item_fun=operations
            )

        except Exception as e:
            AntLogger.error(f"获取设置表格数据失败: {e}")
            exc_type, exc_obj, exc_tb = sys.exc_info()
            AntLogger.error(f"获取设置表格数据失败: {e}")
            AntLogger.error(
                f"文件名: {exc_tb.tb_frame.f_code.co_filename}, 行号: {exc_tb.tb_lineno}"
            )
            # 返回空表格
            return TableDataDto(
                table_header=headers,
                table_data=[],
                table_item_fun=[
                    {"编辑": self.edit_setting},
                    {"删除": self.delete_setting},
                ],
            )

    def getBaseParam(self):
        """获取基本参数"""
        return {"search_key": self.searchKey}

    def search_settings(self, search_text):
        """搜索设置"""
        self.searchKey = search_text
        self.refreshDataForTemplate("系统设置列表")
        return "搜索成功"

    def add_new_setting(self):
        """添加新设置"""
        # 定义表单配置
        form_config = [
            {"type": "text", "label": "键名", "name": "key", "required": True},
            {"type": "text", "label": "值", "name": "value"},
            {"type": "text", "label": "描述", "name": "desc"},
        ]

        # 添加自定义表单
        self.addCustomBox(
            title="新增设置",
            form_config=form_config,
            on_submit=self._handle_add_setting,
            style_file="form_style.qss",
        )

        return "打开新增设置表单"

    def _handle_add_setting(self, form_data):
        """处理新增设置表单提交"""
        try:
            key = form_data.get("key", "")
            value = form_data.get("value", "")
            desc = form_data.get("desc", "")

            if not key:
                return "键名不能为空"

            # 保存设置
            self.dataMapService.save_or_update_common_setting(key, value, desc)

            # 刷新表格数据
            self.refreshDataForTemplate("系统设置列表")

            return "设置添加成功"
        except Exception as e:
            AntLogger.error(f"添加设置失败: {e}")
            return f"添加设置失败: {str(e)}"

    def edit_setting(self, key):
        """编辑设置"""
        try:
            # 获取设置
            setting = self.dataMapService._setting_das.get_setting_by_key(key)
            if not setting:
                return f"未找到键为 {key} 的设置"

            # 定义表单配置
            form_config = [
                {"type": "hidden", "name": "key", "value": setting.setting_key},
                {
                    "type": "text",
                    "label": "键名",
                    "name": "key_display",
                    "value": setting.setting_key,
                    "disabled": True,
                },
                {
                    "type": "text",
                    "label": "值",
                    "name": "value",
                    "value": setting.setting_value or "",
                },
                {
                    "type": "text",
                    "label": "描述",
                    "name": "desc",
                    "value": setting.setting_desc or "",
                },
            ]

            # 添加自定义表单
            self.addCustomBox(
                title=f"编辑设置: {setting.setting_key}",
                form_config=form_config,
                on_submit=self._handle_edit_setting,
                style_file="form_style.qss",
            )

            return "打开编辑设置表单"
        except Exception as e:
            AntLogger.error(f"打开编辑设置表单失败: {e}")
            return f"打开编辑设置表单失败: {str(e)}"

    def _handle_edit_setting(self, form_data):
        """处理编辑设置表单提交"""
        try:
            key = form_data.get("key", "")
            value = form_data.get("value", "")
            desc = form_data.get("desc", "")

            if not key:
                return "键名不能为空"

            # 更新设置
            self.dataMapService.save_or_update_common_setting(key, value, desc)

            # 刷新表格数据
            self.refreshDataForTemplate("系统设置列表")

            return "设置更新成功"
        except Exception as e:
            AntLogger.error(f"更新设置失败: {e}")
            return f"更新设置失败: {str(e)}"

    def delete_setting(self, key):
        """删除设置"""
        try:
            # 删除设置
            success = self.dataMapService.delete_setting(key)

            # 刷新表格数据
            self.refreshDataForTemplate("系统设置列表")

            if success:
                return f"设置 {key} 已删除"
            else:
                return f"删除设置 {key} 失败"
        except Exception as e:
            AntLogger.error(f"删除设置失败: {e}")
            return f"删除设置失败: {str(e)}"

    def refresh_data(self):
        """刷新数据"""
        self.refreshDataForTemplate("系统设置列表")
        return "数据已刷新"
